<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :model="formData" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="结算单位" v-bind="validateInfos.company">
            <a-input v-model:value="formData.company" placeholder="请输入结算单位" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="保险公司" v-bind="validateInfos.insurance">
            <j-dict-select-tag v-model:value="formData.insurance" dictCode="BXGS" placeholder="请选择保险公司" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="结算规则" v-bind="validateInfos.rule">
            <j-dict-select-tag v-model:value="formData.rule" dictCode="SC_JSGZ" placeholder="请选择结算规则" :disabled="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="5"><div :style="{ textAlign: 'right', marginRight: '6px' }">结算地区: </div></a-col>
        <a-col :span="19">
          <div v-for="(areaConfig, index) in formData.configs" :key="index" class="areas-div">
            <a-button danger class="delete-btn" @click="deleteSettlementAreas(index)">删除</a-button>
            <a-form-item
              :name="['configs', index, 'platform']"
              label="平台"
              :labelCol="{ span: 3 }"
              :rules="{
                required: true,
                message: '请选择平台',
              }"
            >
              <PlatformTree multiple v-model:model-value="areaConfig.platform" :disabled="disabled" />
            </a-form-item>
            <a-form-item
              :name="['configs', index, 'type']"
              label="经纪费比例类型"
              :labelCol="{ span: 7 }"
              :rules="{
                required: true,
                message: '选择经纪费比例类型',
              }"
            >
              <a-radio-group v-model:value="areaConfig.type" :disabled="disabled">
                <a-radio value="SOLITARY">非阶梯经纪费比例</a-radio>
                <a-radio value="LEVEL">阶梯经纪费比例</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-if="areaConfig.type === 'SOLITARY'"
              :name="['configs', index, 'fixRate']"
              label="非阶梯经纪费比例"
              :labelCol="{ span: 7 }"
              :rules="{
                required: true,
                message: '输入非阶梯经纪费比例',
              }"
            >
              <a-input-number
                :style="{ width: '200px' }"
                v-model:value="areaConfig.fixRate"
                step="0.000001"
                max="1"
                :disabled="disabled"
                placeholder="请输入非阶梯经纪费比例"
              />
            </a-form-item>
            <div class="stepRatioDiv" v-if="areaConfig.type === 'LEVEL'">
              <div :style="{ marginBottom: '10px' }">
                <span class="label">小于</span>
                <a-input-number v-model:value="formData.configs[index].min.value" :disabled="disabled" />
                <span class="label" :style="{ marginLeft: '10px' }">比例</span>
                <a-input-number v-model:value="formData.configs[index].min.rate" step="0.000001" max="1" :disabled="disabled"
              /></div>
              <div :style="{ marginBottom: '10px' }">
                <span class="label">大于</span>
                <a-input-number v-model:value="formData.configs[index].max.value" :disabled="disabled" />
                <span class="label" :style="{ marginLeft: '10px' }">比例</span>
                <a-input-number v-model:value="formData.configs[index].max.rate" step="0.000001" max="1" :disabled="disabled"
              /></div>
              <div :style="{ marginBottom: '10px' }" v-for="(item, stepIndex) in areaConfig.steps" :key="stepIndex">
                <span class="label">范围{{ stepIndex + 1 }}:</span>
                <a-input-number v-model:value="item.lgt" :disabled="disabled" />
                ～
                <a-input-number v-model:value="item.lt" :disabled="disabled" />
                <span class="label label-right">经纪费比例:</span>
                <a-input-number v-model:value="item.rate" step="0.000001" max="1" :disabled="disabled" />
                <a-button @click="deleteConfigStep(index, stepIndex)">删除</a-button>
              </div>
              <a-button @click="addConfigStep(index)" class="add-btn">添加阶梯</a-button>
            </div>
          </div>
          <a-button @click="addSettlementAreas" class="add-areas">添加结算地区</a-button>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { loadTreeData } from '/@/api/common/api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { saveOrUpdate } from '../InsuranceSettlementConfig.api';
  import { Form } from 'ant-design-vue';
  import PlatformTree from "/@/components/BusinessComponents/PlatformTree.vue";

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    insurance: '',
    company: '',
    configs: [
      {
        fixRate: undefined,
        platform: Array,
        type: undefined,
        max: {
          value: '',
          rate: '',
        },
        min: {
          value: '',
          rate: '',
        },
        steps: [
          {
            lgt: '',
            lt: '',
            rate: '',
          },
        ],
      },
    ],

    rule: 'PAY',
  });
  const areaTreeData = ref([]);
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    insurance: [{ required: true, message: '请输入选择公司!' }],
    company: [{ required: true, message: '请输入结算单位!' }],
    rule: [{ required: true, message: '请输入结算规则!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  onMounted(() => {
    loadTreeData({ pcode: 'B04' }).then((res) => {
      if (res) {
        areaTreeData.value = res;
        // 默认展开父节点
        //expandedKeys.value = unref(departTree).map(item => item.id)
      }
    });
  });
  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  function addConfigStep(index) {
    // 新增
    formData.configs[index].steps.push({
      lgt: '',
      lt: '',
      rate: '',
    });
  }
  function deleteConfigStep(index, stepIndex) {
    // 删除
    formData.configs[index].steps.splice(stepIndex, 1);
  }
  function addSettlementAreas() {
    formData.configs.push({
      max: {
        value: '',
        rate: '',
      },
      min: {
        value: '',
        rate: '',
      },
      steps: [
        {
          lgt: '',
          lt: '',
          rate: '',
        },
      ],
    });
  }
  function deleteSettlementAreas(index) {
    formData.configs.splice(index, 1);
  }
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      const configs = record.configs.map((item) => {
        if (item.type === 'LEVEL') {
          return {
            ...item,
            max: item.trendsRateConfig.max,
            min: item.trendsRateConfig.min,
            steps: item.trendsRateConfig.interval,
          };
        }
        return {
          ...item,
        };
      });
      Object.assign(formData, { ...record, configs });
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    console.log('submitForm', formData);

    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    const { id, insurance, company, configs, rule } = model;
    if (!configs || configs.length === 0) {
      createMessage.warning('请添加结算地区');
      return;
    }
    const configsParams = configs.map((item: any) => {
      const { fixRate,platform, type, max, min, steps } = item;
      if (type === 'LEVEL') {
        return {
          platform,
          type,
          trendsRateConfig: {
            max,
            min,
            interval: steps,
          },
        };
      }
      return {
        platform,
        fixRate,
        type,
      };
    });
    const params: any = {
      insurance,
      company,
      rule,
      configs: configsParams,
    };
    if (id) params.id = id;

    //循环数据
    await saveOrUpdate(params, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
  .add-areas {
    // margin-top: 10px;
  }
  .areas-div {
    border: 1px solid #cfe5fc;
    padding: 20px;
    margin-bottom: 10px;
    position: relative;
    .delete-btn {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }
  .label {
    margin-right: 10px;
  }
  .label-right {
    margin-left: 20px;
  }
  .add-btn {
    margin-top: 10px;
  }
  .stepRatioDiv {
    padding: 20px;
    background-color: #f6f6f6;
  }
</style>
